import React, { useState } from "react";
import axios from "axios";
import "./style.css";
import { useNavigate } from "react-router-dom";
import { useAppDispatch } from "../../app/hooks";
import { login } from "../../app/module/user/userSlice";
const Index: React.FC = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const dispatch = useAppDispatch();

  const navigate = useNavigate();
  const onLogin = async () => {
    dispatch(
      login({
        username,
        password,
      })
    )
      .then((resp) => {
        localStorage.setItem("token", resp.payload.token);
        navigate("/");
      })
      .catch(() => {
        alert("登录失败, 请重新登录");
      });
  };

  const onReset = () => {
    setUsername("");
    setPassword("");
  };

  return (
    <div className="login">
      <h2>用户登录</h2>
      <input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
        placeholder="请输入用户名"
      />
      <input
        type="text"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="请输入密码"
      />
      <button onClick={onLogin}>登录</button>
      <button onClick={onReset}>重置</button>
    </div>
  );
};

export default Index;
